/* eslint-disable react/jsx-props-no-spreading */
/**

*/

import { QuestionCircleOutlined } from '@ant-design/icons';

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';

import { Row, Col, message, Input, Tooltip } from 'antd';
import { connect } from 'dva';
import React, { PureComponent } from 'react';
import 'moment/locale/zh-cn';

import OperatePageC from './OperatePageC';
import TableForm from './TableForm';

import { PrimaryC, DATA_ENTRY, AdvancedSearch, ContentPackage, ModalC } from '../../../comps';
import { getUserInfo } from '../../../utils/commonFunc';

const FormItem = Form.Item;

@Form.create()
class UserManageNew extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isReset: false, // 判断是否点击重置
      operatePageVisible: false, // 新增或编辑页的显示隐藏
      currentPage: 1,
      numInPage: 10,
      superMan: undefined,
      titleModal: '',
      editItem: undefined, // 编辑
      oldTreeDate: undefined, // 存储关联组合数据
      resetModalVisible: false, // 重置的显示隐藏
      resetItem: undefined, // 重置的item
      userIdData: undefined, // 用户id列表
      searchItem: {
        userActive: '0',
      }, // 搜索内容
      isZiGuan: false, // 是否是资管环境
      defaultQuery: false, // 关联组合查询权限全选多选框默认值
      defaultOperation: false, // 关联组合查询权限全选多选框默认值
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { superMan } = this.state;
    const temp = getUserInfo();
    this.setState(
      {
        superMan: temp.isSuper,
      },
      () => {
        if (temp.isSuper) {
          dispatch({
            type: 'userManageNewM/getTenantList',
            payload: {},
          });
        }
      },
    );

    // 获取用户表格数据
    dispatch({
      type: 'userManageNewM/Search',
      payload: {
        userActive: 'Y',
      },
    });

    // 获取岗位列表
    dispatch({
      type: 'userManageNewM/SearchStation',
      payload: {},
    });
    // 获取角色列表
    dispatch({
      type: 'userManageNewM/SearchRole',
      payload: {},
    });

    const {
      globalM: {
        dataDictionary: { OperatorNumber = [] },
      },
    } = this.props;
    // 字典接口
    dispatch({
      type: 'userManageNewM/getDictionList',
      // [通道标识]
      payload: {
        OperatorNumber,
      },
    });
  }

  // 表格页码排序改变调用
  changeReset = (current, pagesize) => {
    const { isReset } = this.state;
    if (isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this.setState({
        isReset: false,
      });
      return;
    }
    this.setState({
      currentPage: current,
      numInPage: pagesize,
    });
  };

  //   新增按钮点击事件
  addClick = () => {
    const { dispatch } = this.props;
    const { oldTreeDate } = this.state;
    this.setState(
      {
        operatePageVisible: true,
        titleModal: '新增用户',
      },
      () => {
        if (!(oldTreeDate && oldTreeDate.length != 0)) {
          dispatch({
            type: 'userManageNewM/cpTreeDateAll',
            payload: {},
            callback: (type, res) => {
              if (type == 'success') {
                // 初始 查询全选不勾选
                let queryFlag = false;
                let operationFlag = false;
                if (res && res.length) {
                  // 判断查询,操作全选权限勾选框 初始值
                  let tempQueryArr = [];
                  let tempOperateArr = [];

                  tempQueryArr = this.generatorValue('queryPermission', res, tempQueryArr);
                  tempOperateArr = this.generatorValue('operationPermission', res, tempOperateArr);
                  queryFlag = this.isEqualData(tempQueryArr);
                  operationFlag = this.isEqualData(tempOperateArr);
                }
                this.setState({
                  oldTreeDate: res,
                  defaultQuery: queryFlag,
                  defaultOperation: operationFlag,
                });
              }
            },
          });
        }
      },
    );
    // 获取机构列表
    dispatch({
      type: 'userManageNewM/getOrganizationData',
      payload: {},
    });
  };

  // 新增编辑页返回主页
  onBack = (msg, type) => {
    const { searchItem } = this.state;
    this.setState({
      operatePageVisible: msg,
    });
    if (type == 'ok') {
      this.searchById(searchItem);
    }
  };

  // 根据查询条件搜索
  searchByitem = () => {
    const { searchItem } = this.state;
    const values = {
      userId: searchItem?.name || '',
      tenantId: searchItem?.tenantId || '',
      userActive: searchItem?.userActive == '0' ? 'Y' : 'N',
      stationId: searchItem?.stationId || '',
      roleId: searchItem?.roleId || '',
    };
    this.props.dispatch({
      type: 'userManageNewM/Search',
      payload: values,
    });
    if (localStorage.getItem('antd-pro-superMan') == 'true') {
      this.props.dispatch({
        type: 'userManageNewM/getTenantList',
        payload: {},
        callback: (i) => {},
      });
    }
  };

  /* ***************查询条件部分*************** */
  // 查询事件
  searchById = (e) => {
    const { dispatch } = this.props;
    this.setState(
      {
        currentPage: 1,
        numInPage: 10,
        isReset: false,
      },
      () => {
        if (e && e.name != undefined) {
          e.name = e.name.trim();
        }
        const values = {
          userId: e?.name || '',
          tenantId: e?.tenantId || '',
          userActive: e?.userActive == '0' ? 'Y' : 'N',
          stationId: e?.stationId || '',
          roleId: e?.roleId || '',
        };
        dispatch({
          type: 'userManageNewM/Search',
          payload: values,
        });
      },
    );
  };

  // 重置
  handleFormReset = () => {
    this.setState({
      isReset: true,
      searchItem: {
        userActive: '0',
      },
    });
  };

  // 查询条件展示
  showMainPage = () => {
    const { superMan } = this.state;
    const {
      userManageNewM: { stationData, roleData },
    } = this.props;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'name',
          title: '名称或账户',
          type: DATA_ENTRY.INPUT,
          placeholder: '请输入用户名或账号进行模糊搜索',
          allowClear: true,
          showSearch: true,
          // onChange: e => { this.searchOnChange(e) },
        },
        {
          dataIndex: 'tenantId',
          title: '租户',
          type: DATA_ENTRY.TENANT,
          hide: !superMan,
          // onChange: e => { this.tenantOnChange(e) },
        },
        {
          dataIndex: 'stationId',
          title: '岗位',
          type: DATA_ENTRY.SELECT,
          dataSource: stationData,
          isMultiple: true,
          allowClear: true,
          filterOption: (input, option) => {
            return option.props.children.toLowerCase().indexOf(input.toLowerCase()) > -1;
          },
        },
        {
          dataIndex: 'roleId',
          title: '角色',
          type: DATA_ENTRY.SELECT,
          dataSource: roleData,
          isMultiple: true,
          allowClear: true,
          filterOption: (input, option) => {
            return option.props.children.toLowerCase().indexOf(input.toLowerCase()) > -1;
          },
        },
        {
          dataIndex: 'userActive',
          title: '账户是否冻结',
          type: DATA_ENTRY.SELECT,
          isTrueFalseJudge: true,
          initialValue: '0',
        },
      ],
      // 点击查询按钮
      onQuery: (e) => {
        this.setState({
          searchItem: e,
        });
        this.searchById(e);
      },
      onClear: () => {
        // 点击重置按钮
        this.handleFormReset();
      },
    };
    return (
      <div>
        <div style={{ marginBottom: '10px' }}>
          <AdvancedSearch {...searchProps} />
        </div>
        <PrimaryC title='新增' style={{ margin: '0 10px 10px 10px' }} onClick={this.addClick} />
      </div>
    );
  };

  /* ***************\查询条件部分*************** */
  resetInfo = () => {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 6, offset: 0 },
        sm: { span: 10, offset: 0 },
        md: { span: 10, offset: 0 },
        lg: { span: 10, offset: 0 },
        xl: { span: 9, offset: 0 },
        xxl: { span: 7, offset: 0 },
      },
      wrapperCol: {
        xs: { span: 16, offset: 0 },
        sm: { span: 12, offset: 0 },
        md: { span: 12, offset: 0 },
        lg: { span: 12, offset: 0 },
        xl: { span: 13, offset: 0 },
        xxl: { span: 15, offset: 0 },
      },
    };
    return (
      <Form>
        <Row style={{ margin: '10px 0' }}>
          <Col>
            <FormItem
              label={
                <span>
                  新密码&nbsp;
                  <Tooltip title='密码长度8-128，且至少包含数字、大写字母、小写字母、特殊字符四类中的三类！'>
                    <QuestionCircleOutlined />
                  </Tooltip>
                </span>
              }
              {...formItemLayout}
            >
              {getFieldDecorator('newPassword', {
                rules: [
                  { required: true, message: '请输入新密码' },
                  {
                    pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,128}$/,
                    // message: '密码长度8-128，且至少包含数字、大写字母、小写字母、特殊字符四类中的三类！' }
                    message: '输入密码格式不正确！',
                  },
                ],
                validateTrigger: 'onBlur',
              })(<Input placeholder='请输入新密码' />)}
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  };

  resetOk = () => {
    const {
      form: { validateFields },
      dispatch,
    } = this.props;
    const { resetItem } = this.state;
    validateFields(['newPassword'], (err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'userManageNewM/resetPassWord',
        payload: {
          userId: resetItem.userAccount,
          newPassWord: fieldsValue.newPassword,
        },
        callback: (res) => {
          if (res == 'success') {
            this.searchByitem();
            this.setState({
              resetModalVisible: false,
            });
          }
        },
      });
    });
  };

  resetCancel = () => {
    const {
      form: { resetFields },
    } = this.props;
    resetFields('newPassword');
    this.setState({
      resetModalVisible: false,
    });
  };

  // 递归树形结构，判断所有数据的同一属性值是否相等 遍历所有该属性值,放在数组中返回
  generatorValue = (valueName, treeData, result) => {
    // eslint-disable-next-line no-restricted-syntax, no-unused-vars
    for (const item of treeData) {
      if (item.children != null && item.children.length) {
        this.generatorValue(valueName, item.children, result);
      }
      result.push(item[valueName]);
    }
    return result;
  };

  // 判断数组所有值是否都相等,相等返回a[0]即第一个元素,不相等返回false
  isEqualData = (tempArr) => {
    const firstData = tempArr[0];
    const isEquality = tempArr.every((val) => val === firstData);
    if (isEquality) {
      return firstData;
    }
    return false;
  };

  render() {
    const { operatePageVisible, superMan, isZiGuan } = this.state;
    const { form, dispatch, loading } = this.props;
    const {
      userManageNewM: { tenantData, data },
    } = this.props;
    const table = {
      superMan,
      data,
      isZiGuan,
      // 删除
      onDeleteFrom: (item) => {
        dispatch({
          type: 'userManageNewM/deleteUser',
          payload: item,
          callback: (res) => {
            if (res == 'success') {
              this.searchByitem();
            }
          },
        });
      },
      // 解锁
      onUnlockFrom: (item) => {
        dispatch({
          type: 'userManageNewM/unLockUser',
          payload: {
            userId: item.userAccount,
          },
          callback: (res) => {
            if (res == 'success') {
              this.searchByitem();
            }
          },
        });
      },
      // 解冻
      onUnfreezeFrom: (item) => {
        dispatch({
          type: 'userManageNewM/updateActiveState',
          payload: {
            userId: item.userAccount,
          },
          callback: (res) => {
            if (res == 'success') {
              this.searchByitem();
            }
          },
        });
      },
      // 冻结
      onFreezeFrom: (item) => {
        dispatch({
          type: 'userManageNewM/updateActiveState',
          payload: {
            userId: item.userAccount,
          },
          callback: (res) => {
            if (res == 'success') {
              this.searchByitem();
            }
          },
        });
      },
      // 重置密码
      onResetFrom: (item) => {
        const {
          form: { resetFields },
        } = this.props;
        resetFields('newPassword');
        this.setState({
          resetModalVisible: true,
          resetItem: item,
        });
      },
      // 编辑状态下
      onEditFrom: (item) => {
        const editInstitution = [];
        const editStation = [];
        const editRole = [];
        item.institutionModels &&
          item.institutionModels.forEach((items) => {
            editInstitution.push(items.id);
          });
        item.stationModels &&
          item.stationModels.forEach((items) => {
            editStation.push(items.id);
          });
        item.roleModels &&
          item.roleModels.forEach((items) => {
            editRole.push(items.id);
          });
        item.editInstitution = editInstitution;
        item.editStation = editStation;
        item.editRole = editRole;
        this.setState({
          editItem: item,
        });
        form.resetFields();
        if (item.tenant) {
          // 获取机构列表
          dispatch({
            type: 'userManageNewM/getOrganizationData',
            payload: {
              tenantId: item.tenant,
            },
          });
        } else {
          dispatch({
            type: 'userManageNewM/getOrganizationData',
            payload: {},
          });
        }

        this.setState(
          {
            operatePageVisible: true,
            titleModal: '编辑用户',
          },
          () => {
            dispatch({
              type: 'userManageNewM/cpTreeDate',
              payload: {
                userId: item.userId,
              },
              callback: (type, res) => {
                if (type == 'success') {
                  // 初始 查询全选不勾选
                  let queryFlag = false;
                  let operationFlag = false;
                  if (res && res.length) {
                    // 判断查询,操作全选权限勾选框 初始值
                    let tempQueryArr = [];
                    let tempOperateArr = [];
                    tempQueryArr = this.generatorValue('queryPermission', res, tempQueryArr);
                    tempOperateArr = this.generatorValue('operationPermission', res, tempOperateArr);
                    queryFlag = this.isEqualData(tempQueryArr);
                    operationFlag = this.isEqualData(tempOperateArr);
                    this.$operatePageC.onChangestate(queryFlag, operationFlag);
                  }
                  this.setState({
                    // oldTreeDate: res,
                    defaultQuery: queryFlag,
                    defaultOperation: operationFlag,
                  });
                }
              },
            });
          },
        );
      },
    };
    const operateData = {
      oldTreeDate: this.state.oldTreeDate,
      editItem: this.state.editItem,
      defaultQuery: this.state.defaultQuery,
      defaultOperation: this.state.defaultOperation,
      tenantData,
      superMan,
      titleModal: this.state.titleModal,
    };
    return (
      <ContentPackage
        title='用户配置'
        contentHtml={
          <div style={{ height: '100%' }}>
            <div style={{ display: operatePageVisible ? 'none' : 'block' }}>
              {this.showMainPage()}
              <TableForm {...table} changeReset={this.changeReset} currentPage={this.state.currentPage} numInPage={this.state.numInPage} />
            </div>
            {operatePageVisible ? (
              <div style={{ height: '100%' }}>
                <OperatePageC
                  {...operateData}
                  onBack={this.onBack}
                  onRef={(ref) => {
                    this.$operatePageC = ref;
                  }}
                />
              </div>
            ) : (
              ''
            )}
            <ModalC
              title='重置密码'
              visible={this.state.resetModalVisible}
              maskClosable={false}
              onOk={this.resetOk}
              confirmLoading={loading.effects['userManageNewM/resetPassWord'] == true}
              onCancel={this.resetCancel}
              width={400}
            >
              {this.resetInfo()}
            </ModalC>
          </div>
        }
      />
    );
  }
}
export default connect(({ userManageNewM, loading, globalM }) => ({
  userManageNewM,
  loading,
  globalM,
}))(UserManageNew);
